package org.liulinlin.sejw.db;

import java.sql.*;

/*
import org.osoa.sca.annotations.Service;
import org.osoa.sca.annotations.Init;
import org.osoa.sca.annotations.Destroy;
import org.osoa.sca.annotations.Property;
*/

/**
 * 数据访问服务，不在composite里定义相应的component。需要数据访问的，就继承此类。
 * @author kodylau
 *
 */
//@Service(DataAccessService.class)
public class DataAccessServiceImpl{
	/**
	 * Default database url, username, password.
	 * Configurable. Maybe use some set property method.
	 */
	//@Property
	protected String databaseURL = "jdbc:mysql://localhost:3306/shipping_export";
	
	//@Property
	protected String username = "kodylau";
	
	//@Property
	protected String pwd = "123";
	
	protected static Connection connection;
	
	/**
	 * Connect database.
	 */
	//@Init
	public DataAccessServiceImpl() {
		try {
			//Register the JDBC driver for MySQL.
			Class.forName("com.mysql.jdbc.Driver");
			System.out.println("Connecting to database: " + databaseURL + " ...");
			connection = DriverManager.getConnection(databaseURL, username, pwd);
			System.out.println("Database connection succeed.");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void init() {
		try {
			//Register the JDBC driver for MySQL.
			Class.forName("com.mysql.jdbc.Driver");
			System.out.println("Connecting to database: " + databaseURL + " ...");
			connection = DriverManager.getConnection(databaseURL, username, pwd);
			System.out.println("Database connection succeed.");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * Release database connection.
	 */
	//@Destroy
	public void shutdown() {
		if (connection != null) {
			try {
				connection.close();
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				connection = null;
			}
		}
	}
	
	/**
	 * 数据库查询，返回查询结果java.sql.ResultSet
	 * @param sql
	 * @return
	 */
	public static ResultSet query(String sql) {
		//init();
		ResultSet res = null;
		try {
			Statement stmt = connection.createStatement();
			res = stmt.executeQuery(sql);
			System.out.println("Query: " + sql + " done.");
			//return res;
		} catch (Exception e) {
			System.out.println("DataAccessServiceImpl.query");
			e.printStackTrace();
		} finally {
			//shutdown();
		}
		return res;
	}
	
	/**
	 * 数据库更新，insert, delete, alter等操作
	 */
	public static void update(String sql) {
		//init();
		try {
			Statement stmt = connection.createStatement();
			stmt.executeUpdate(sql);
			System.out.println("Update: " + sql + " done.");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			//shutdown();
		}
	}
}

